﻿using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;

using Xc.DataAccess.Core;
using Xc.DataAccess.HyperTerminalCore.Models;

namespace Xc.DataAccess.HyperTerminalCore.Services
{
    /// <summary>
    /// TCP客户端服务
    /// </summary>
    public class TcpClientService : ITcpClientService
    {
        /// <summary>
        /// 打开并连接到服务器
        /// </summary>
        /// <param name="tcpClientOption"></param>
        /// <returns></returns>
        public async Task<Result> OpenAsync(TcpClientOption tcpClientOption)
        {
            try
            {
                if (ClientInfo != null)
                {
                    ClientInfo.Close();
                }
                var client = new TcpClient();
                await client.ConnectAsync(tcpClientOption.HostName, tcpClientOption.Port);
                ClientInfo = new TcpClientInfo(client, tcpClientOption.Encoding);
                ClientInfo.BeginRead();
                return Result.Accept("打开成功");
            }
            catch (Exception err)
            {
                return Result.Reject(err.Message);
            }
        }
        /// <summary>
        /// 客户端信息
        /// </summary>
        public ITcpClientInfo ClientInfo { get; private set; }
        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        public Result Close()
        {
            ClientInfo.Close();
            return Result.Accept("关闭成功");
        }
    }
}
